/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainWindow.java
 *
 * Created on 16.01.2012, 10:29:30
 */
package promogui;

import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.Box.Filler;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import org.jfree.chart.ChartPanel;

/**
 *
 * @author Cryptkeeper
 */
public class PromoGUIMain extends javax.swing.JFrame {

    private ArrayList<Project> projects;
    private ArrayList<HealthCriteria> criterias;
    
    private ProjectsOverviewChart chartGen;
    private Engineer engineer;
    private InputTablePanel deltaPanel;
    private JPanel healthCriteriaPanel;
    private JPanel chartSelectionPanel;
    private JPanel homePanel;
    private int viewIndexOverview;
    private int viewIndexProject;
           
    private boolean isManager;
    
    private AbstractAction addWeekAction;
    
    private javax.swing.JButton addHealthCriteriaButton;
    private javax.swing.JComboBox healtCriteriaSelection;
    private javax.swing.JComboBox chartSelection;
    
    /** Creates new form MainWindow */
    public PromoGUIMain() {
        
        super("Project Monitor");
        
        EventQueue queue = Toolkit.getDefaultToolkit().getSystemEventQueue();
        queue.push(new EventQueueProxy());
        
        criterias = new ArrayList<HealthCriteria>();
        isManager = false;
        
        this.setIconImage(Toolkit.getDefaultToolkit().getImage( "promoicon.png" ));
        
        try {
            
            projects = CSVIO.getProjects();
            chartGen = new ProjectsOverviewChart(projects);
            engineer = new Engineer("Bill");
            
            
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
       
        
        addWeekAction = new AddWeekAction("addWeekIcon.png");
        
        HealthCriteria criteria = new HealthCriteria(2, 0, 255, 1, false, 0.0, true, 0.5, "Bugs/LOC" );
        
        this.criterias.add(criteria);
        
        initComponents();
        
        homePanel = new JPanel(new java.awt.BorderLayout());
        healthCriteriaPanel = new JPanel(new java.awt.FlowLayout());
        
        healthCriteriaPanel.setBackground(Color.white);
        
        healtCriteriaSelection = new JComboBox();
        
        healtCriteriaSelection.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                criteriaSelectionChanged(evt);
            }
        });
        
        
        chartSelectionPanel = new JPanel(new java.awt.FlowLayout());
        chartSelectionPanel.setBackground(Color.white);
        
        chartSelection = new JComboBox();
        
        updateCriteriaSelection();
        
        chartSelection.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                chartSelectionChanged(evt);
            }
        });
        
        
        addHealthCriteriaButton = new JButton("Hinzufügen");
        addHealthCriteriaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addHealthCriteriaButtonkActionPerformed(evt);
            }
        });
        
        healthCriteriaPanel.add(new JLabel("Gesundheitskriterium:"));
        healthCriteriaPanel.add(healtCriteriaSelection);
        healthCriteriaPanel.add(addHealthCriteriaButton);
        
        chartSelectionPanel.add(new JLabel("Ansicht:"));
        chartSelectionPanel.add(chartSelection);
        
        // projectList.setSelectedIndex(0);   ??
        jTree1.setSelectionRow(0);

        
        
        
        
        
        
        HomeAction homeAction = new HomeAction();
        
        this.jToolBar1.add(new PreviousAction(null) );
        this.jToolBar1.add(homeAction);
        this.jToolBar1.add(new NextAction(null) );
        
        //jToolBar1.addSeparator();
        
        
        this.jToolBar1.add(addWeekAction);
        
        Component horizontalGlue = Box.createHorizontalGlue();
        jToolBar1.add(horizontalGlue);
        
        
        JComboBox userList = new JComboBox();
        userList.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bill", "Tom", "Eric", "Ada", "Steve", "John (Manager)" }));       
                
        userList.addItemListener( new ItemListener() {
            public void itemStateChanged( ItemEvent e ) 
            {
              
                if (e.getStateChange() == 1) 
                {
                  
                    JComboBox selectedChoice = (JComboBox)e.getSource();
                    switch (selectedChoice.getSelectedIndex())
                    {
                        case 0:
                            isManager = false;
                            login(new Engineer("Bill"));                         
                            break;
                        case 1:
                            isManager = false;
                            login(new Engineer("Tom"));
                            break;
                        case 2:
                            isManager = false;
                            login(new Engineer("Eric"));
                            break; 
                        case 3:
                            isManager = false;
                            login(new Engineer("Ada"));
                            break; 
                        case 4:
                            isManager = false;
                            login(new Engineer("Steve"));
                            break;     
                        case 5:
                            isManager = true;
                            login(new Engineer("John"));
                            break;   
                  }
              }
          }
        } );
        
        this.jToolBar1.add(new JLabel("Login: "));        
        this.jToolBar1.add(userList);
        
        home();
        
        
        
        this.setSize(640, 480);
        
        jTree1.setSelectionRow(1);
        
        jTree1.setSelectionRow(0);
        //this.jTree1ValueChanged(null);
       pack();
       
       
       
       
       
    }
    
    private void addHealthCriteriaButtonkActionPerformed(java.awt.event.ActionEvent evt)
    {
        new GenerateHealthCriteria(this).setVisible(true);
    }
    
    private void login(Engineer engineer)
    {
        this.engineer = engineer;
        jTree1ValueChanged(null);
        
        //projectList.setSelectedIndex(projectList.getSelectedIndex());
    }
    
    public void addCriteria(HealthCriteria criteria)
    {
        criterias.add(criteria);
        updateCriteriaSelection();
        healtCriteriaSelection.setSelectedIndex(healtCriteriaSelection.getModel().getSize() -1);
    }
    
    private void updateCriteriaSelection()
    {
        int criteriaCount = this.criterias.size();
        
        String [] criteriaNames = new String[criteriaCount + 1];
        String [] chartNames = new String[criteriaCount + 3];
        
        criteriaNames[0] = "Im Zeitplan";
        chartNames[0] = "Übersicht";
        chartNames[1] = "Zeitverteilung";
        chartNames[2] = "Details";
        
        for (int i = 0; i < criteriaCount; i++)
        {
            criteriaNames[i+1] = criterias.get(i).getName();
            chartNames[i+3] = criterias.get(i).getName();
        }
        
        healtCriteriaSelection.setModel(new javax.swing.DefaultComboBoxModel(criteriaNames));
        chartSelection.setModel(new javax.swing.DefaultComboBoxModel(chartNames));
    }
    
    private void criteriaSelectionChanged(ItemEvent evt)
    {
        int index = healtCriteriaSelection.getSelectedIndex();
        
        viewIndexProject = index + 2;
        
        if (evt.getStateChange() == 1)
        {
            
            viewIndexOverview = index;
        
            if (index < 1)
            {
                viewIndexProject = 0;
                 home();
            }
            else
            {
                
                HealthCriteria criteria = criterias.get(index - 1);

                projectTab.removeAll();


                ChartPanel overview = ChartGenerator.getCriteriaProjectOverviewChart(criteria, projects);

                projectTab.removeAll();
               homePanel.removeAll();


                homePanel.add(overview, java.awt.BorderLayout.CENTER);
                homePanel.add(healthCriteriaPanel, java.awt.BorderLayout.PAGE_END);

                jSplitPane1.setRightComponent(homePanel);
            }
        }
    }
    
    private void chartSelectionChanged(ItemEvent evt)
    {
        int index = chartSelection.getSelectedIndex();
        ChartPanel chart = null;
        int treeIndex = getSelectedTreeIndex();
        
        viewIndexProject = index;
        
        if ( ((evt != null && evt.getStateChange() == 1) || evt == null) && (treeIndex >= 0))
        {
        
            if (index < 3)
            {
                switch(index)
                {
                    case 0:
                        chart = ChartGenerator.getWorkedChart(projects.get(treeIndex));                    
                        break;
                        
                    case 1:
                        chart = ChartGenerator.getPieOverview(projects.get(treeIndex));
                        break;
                        
                    case 2:
                         chart = ChartGenerator.getDetailWorkedChart(projects.get(treeIndex));
                        break;
                }
                
                viewIndexOverview = 0;
      
                //this.projectTab.setTabComponentAt(0, viewPanel);
            }
            else
            {
                
                HealthCriteria criteria = this.criterias.get(index - 3);
                
                chart =  ChartGenerator.getCriteriaChart(criteria, projects.get(treeIndex));
                viewIndexOverview = index - 2;
             }
            
           JPanel viewPanel = new JPanel(new java.awt.BorderLayout());

           if (projectTab.getTabCount() > 0)
           {
            this.projectTab.setComponentAt(0, viewPanel);
           }
           
           viewPanel.add(chart, java.awt.BorderLayout.CENTER);
           viewPanel.add(chartSelectionPanel, java.awt.BorderLayout.PAGE_END);

        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        loginButtonGroup = new javax.swing.ButtonGroup();
        jSplitPane1 = new javax.swing.JSplitPane();
        projectTab = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        DefaultMutableTreeNode root =
        new DefaultMutableTreeNode("Projekte");

        for (int i = 0; i < projects.size(); i++)
        {
            root.add(new DefaultMutableTreeNode(projects.get(i).getName()));

        }
        jTree1 = new javax.swing.JTree(root);
        jToolBar1 = new javax.swing.JToolBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Project Monitor");

        jSplitPane1.setResizeWeight(0.25);

        projectTab.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                projectTabStateChanged(evt);
            }
        });
        jSplitPane1.setRightComponent(projectTab);

        jTree1.setPreferredSize(new java.awt.Dimension(100, 64));
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane2.setViewportView(jTree1);

        jSplitPane1.setLeftComponent(jScrollPane2);

        getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER);

        jToolBar1.setRollover(true);
        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    private int getSelectedTreeIndex()
    {
        
       TreePath path = jTree1.getSelectionPath();
      
        
       DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
        
       if (selectedNode.getParent() == null)
       {
           return -1;
       }
        
        return selectedNode.getParent().getIndex(selectedNode);
   
    }
    
    
   
private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
 
   int loc = jSplitPane1.getDividerLocation();
    
    TreePath path = jTree1.getSelectionPath();
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
    
     if (selectedNode.getParent() == null)
    {
        home();
    
    }
    else
    {
    
        int index = selectedNode.getParent().getIndex(selectedNode);

        int selectedTab = projectTab.getSelectedIndex();

        if (selectedTab == -1)
        {
            selectedTab = 0;
        }

        projectTab.removeAll();

        jSplitPane1.setRightComponent(projectTab);

        ChartPanel chart;

        chart = ChartGenerator.getWorkedChart(projects.get(index));

        //deltaPanel = new InputTablePanel(projects.get(index), engineer);

        if (isManager)
        {
            deltaPanel = new InputTablePanel(new TotalDeltaInputTableModel(projects.get(index)), isManager);
        }
        else
        {
            deltaPanel = new InputTablePanel(new DeltaInputTableModel(projects.get(index), engineer), isManager);
        }
        
        JPanel panel = new JPanel(new BorderLayout());
        JToolBar toolBar = new JToolBar();

        InputTablePanel estimatedInputPanel = new InputTablePanel(new EstimatedInputTableModel(projects.get(index), engineer), isManager);


        //panel.add(toolBar, java.awt.BorderLayout.PAGE_START);
        panel.add(deltaPanel, java.awt.BorderLayout.CENTER);
        //toolBar.add(fullJustifyAction);

        JPanel viewPanel = new JPanel(new java.awt.BorderLayout());

        viewPanel.add(chart, java.awt.BorderLayout.CENTER);
        viewPanel.add(chartSelectionPanel, java.awt.BorderLayout.PAGE_END);   
        
        JPanel productValues = new ProductValues(projects.get(index));

        //JPanel productValues = null;
        
        projectTab.add("Diamgramme", viewPanel);
        projectTab.add("Produktdaten", productValues);
        projectTab.add("Arbeitszeit", panel);
        projectTab.add("Plandaten", estimatedInputPanel);

        projectTab.setSelectedIndex(selectedTab);
        chartSelection.setSelectedIndex(viewIndexProject);
        
        chartSelectionChanged(null);

     
    }
     
    addWeekAction.setEnabled(false);
     
    if (!isManager)
    {
        if (selectedNode.getParent() != null)
        {
            addWeekAction.setEnabled(true);
        }
        
        addHealthCriteriaButton.setEnabled(false);
    }
    else
    {      
        addHealthCriteriaButton.setEnabled(true);
    }    
     
     jSplitPane1.setDividerLocation(loc);
}//GEN-LAST:event_jTree1ValueChanged

private void projectTabStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_projectTabStateChanged
    
    int selectedTab = projectTab.getSelectedIndex();

        if (selectedTab == -1)
        {
            selectedTab = 0;
        }
    
        if (projectTab.getTabCount() > 0)
        {
            projectTab.setSelectedIndex(selectedTab);
        }
    chartSelection.setSelectedIndex(viewIndexProject);
    
    chartSelectionChanged(null);
}//GEN-LAST:event_projectTabStateChanged
    public void home()
    {
        //int index = getSelectedTreeIndex();
    
        //int selectedTab = projectTab.getSelectedIndex();
        
        addWeekAction.setEnabled(false);
        projectTab.removeAll();
        
        //homePanel = new JPanel(new java.awt.BorderLayout());
        
        homePanel.removeAll();
        
        chartGen = new ProjectsOverviewChart(projects);
          
        ChartPanel overview;
        overview = new ChartPanel(chartGen.getChart());
        
        homePanel.add(overview, java.awt.BorderLayout.CENTER);
        homePanel.add(healthCriteriaPanel, java.awt.BorderLayout.PAGE_END);
        
        
        //projectTab.add("Projekte Übersicht", homePanel); 
        
        jSplitPane1.setRightComponent(homePanel);
        
        if (jTree1.getSelectionCount() > 0)
        {
            jTree1.setSelectionRow(0);
        }
        
        updateCriteriaSelection();
        
        healtCriteriaSelection.setSelectedIndex(viewIndexOverview);
    }

    class HomeAction extends AbstractAction {

        public HomeAction() {
          super("Home", new ImageIcon("Home.png"));
          putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('H',
              Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
          putValue(SHORT_DESCRIPTION, "Projekte Übersicht");
        }

        public void actionPerformed(ActionEvent e) {
            viewIndexOverview = 0;
            viewIndexProject = 0;
            
            home();  
        }
      }
    
    class AddWeekAction extends AbstractAction {

        public AddWeekAction(String icon) {
          super("Home", new ImageIcon(icon));
          putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('H',
              Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
          putValue(SHORT_DESCRIPTION, "Neue Arbeitszeit-Woche hinzufügen");
        }

        public void actionPerformed(ActionEvent e) {
            projectTab.setSelectedIndex(2);
            deltaPanel.addWeek();
        }
      }
    
    class NextAction extends AbstractAction {

        public NextAction(String icon) {
          super("Next", new ImageIcon("next.png"));
          putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('H',
              Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
          putValue(SHORT_DESCRIPTION, "Nächstes Projekt");
        }

        public void actionPerformed(ActionEvent e) {
            int index = getSelectedTreeIndex();
            
            if (index == -1)
            {
                jTree1.setSelectionRow(1);
            }
            else
            {

                index+=2;
                
                if (index > projects.size())
                {
                    index = 0;
                }
                
                jTree1.setSelectionRow(index);
            }
        }
      }
    
    class PreviousAction extends AbstractAction {

        public PreviousAction(String icon) {
          super("Previous", new ImageIcon("previous.png"));
          putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke('H',
              Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
          putValue(SHORT_DESCRIPTION, "Vorheriges Projekt");
        }

        public void actionPerformed(ActionEvent e) {
            
            int index = getSelectedTreeIndex();
            
            if (index == -1)
            {
                jTree1.setSelectionRow(projects.size());
            }
            else
            {

                //index-=1;

                
                if (index < 0)
                {
                    index = projects.size();
                }
                
                jTree1.setSelectionRow(index);
            }
        }
      }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        
        boolean useNimbus = true;
        
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {             
                if ("Nimbus".equals(info.getName()) && useNimbus) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PromoGUIMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PromoGUIMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PromoGUIMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PromoGUIMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>



        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {


                new PromoGUIMain().setVisible(true);
                

            }
        });
    }
    
    class EventQueueProxy extends EventQueue {

	protected void dispatchEvent(AWTEvent newEvent) {
		try {
			super.dispatchEvent(newEvent);
		} catch (Throwable t) {
			t.printStackTrace();
			String message = t.getMessage();

			if (message == null || message.length() == 0) {
				message = "Fatal: " + t.getClass();
			}

			JOptionPane.showMessageDialog(null, t.getClass() + ": " + message, "General Error", JOptionPane.ERROR_MESSAGE);
		}
	}
}

    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTree jTree1;
    private javax.swing.ButtonGroup loginButtonGroup;
    private javax.swing.JTabbedPane projectTab;
    // End of variables declaration//GEN-END:variables
}

